<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">评论管理</h1>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="table-toolbar">
      <div class="table-toolbar-left">
        <el-input
            v-model="searchForm.keyword"
            clearable
            placeholder="搜索商品名称或评论内容"
            style="width: 250px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon>
              <Search/>
            </el-icon>
          </template>
        </el-input>

        <el-select
            v-model="searchForm.rating"
            clearable
            placeholder="评分"
            style="width: 100px"
            @change="handleSearch"
        >
          <el-option :value="1" label="1星"/>
          <el-option :value="2" label="2星"/>
          <el-option :value="3" label="3星"/>
          <el-option :value="4" label="4星"/>
          <el-option :value="5" label="5星"/>
        </el-select>

        <el-select
            v-model="searchForm.status"
            clearable
            placeholder="状态"
            style="width: 100px"
            @change="handleSearch"
        >
          <el-option :value="1" label="显示"/>
          <el-option :value="0" label="隐藏"/>
        </el-select>

        <el-select
            v-model="searchForm.hasReply"
            clearable
            placeholder="回复状态"
            style="width: 120px"
            @change="handleSearch"
        >
          <el-option :value="1" label="已回复"/>
          <el-option :value="0" label="未回复"/>
        </el-select>

        <el-button type="primary" @click="handleSearch">
          <el-icon>
            <Search/>
          </el-icon>
          搜索
        </el-button>

        <el-button @click="handleReset">
          <el-icon>
            <Refresh/>
          </el-icon>
          重置
        </el-button>
      </div>

      <div class="table-toolbar-right">
        <el-button
            :disabled="selectedComments.length === 0"
            type="success"
            @click="handleBatchShow"
        >
          批量显示
        </el-button>

        <el-button
            :disabled="selectedComments.length === 0"
            type="warning"
            @click="handleBatchHide"
        >
          批量隐藏
        </el-button>

        <el-button @click="handleRefresh">
          <el-icon>
            <Refresh/>
          </el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 评论表格 -->
    <div class="table-container">
      <el-table
          v-loading="loading"
          :data="comments"
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"/>

        <el-table-column label="ID" prop="id" width="80"/>

        <el-table-column label="商品名称" prop="productName" width="200"/>

        <el-table-column label="用户" prop="username" width="120"/>

        <el-table-column label="评分" width="140">
          <template #default="{ row }">
            <div class="rating-container">
              <el-rate
                  v-model="row.rating"
                  :colors="['#ff4d4f', '#ff7a45', '#ffa940', '#52c41a', '#1890ff']"
                  :show-score="false"
                  :show-text="false"
                  disabled
                  size="small"
              />
              <span class="rating-text">{{ row.rating }}星</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="评论内容" min-width="250">
          <template #default="{ row }">
            <div class="comment-content">
              <p>{{ formatCommentContent(row.content) }}</p>
              <div v-if="row.images && row.images.length > 0" class="comment-images">
                <img
                    v-for="(image, index) in row.images.slice(0, 3)"
                    :key="index"
                    :src="image"
                    class="comment-image"
                    @click="previewImage(image)"
                />
                <span v-if="row.images.length > 3" class="more-images">
                +{{ row.images.length - 3 }}
              </span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="商家回复" min-width="200">
          <template #default="{ row }">
            <div v-if="row.replyContent" class="merchant-reply">
              <p>{{ row.replyContent }}</p>
              <small>{{ formatDateTime(row.replyTime) }}</small>
            </div>
            <span v-else class="no-reply">未回复</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="评论时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="200">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                  size="small"
                  type="primary"
                  @click="handleReply(row)"
              >
                {{ row.replyContent ? '修改回复' : '回复' }}
              </el-button>

              <el-button
                  v-if="row.status === 1"
                  size="small"
                  type="warning"
                  @click="handleUpdateStatus(row, 0)"
              >
                隐藏
              </el-button>

              <el-button
                  v-else
                  size="small"
                  type="success"
                  @click="handleUpdateStatus(row, 1)"
              >
                显示
              </el-button>

              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="imagePreviewVisible" title="图片预览" width="500px">
      <div class="image-preview-container">
        <img :src="previewImageUrl" alt="预览图片" style="width: 100%; height: auto;"/>
      </div>
    </el-dialog>

    <!-- 回复对话框 -->
    <ReplyDialog
        v-model="replyDialogVisible"
        :comment="selectedComment"
        @success="handleReplySuccess"
    />
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Refresh, Search} from '@element-plus/icons-vue'
import {useCommentStore} from '@/store/comment'
import {formatDateTime} from '@/utils'
import ReplyDialog from './ReplyDialog.vue'

// Store
const commentStore = useCommentStore()

// 响应式数据
const searchForm = reactive({
  keyword: '',
  rating: null,
  status: null,
  hasReply: null
})

const selectedComments = ref([])
const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')
const replyDialogVisible = ref(false)
const selectedComment = ref(null)

// 计算属性
const comments = computed(() => commentStore.comments)
const loading = computed(() => commentStore.loading)
const total = computed(() => commentStore.total)
const currentPage = computed({
  get: () => commentStore.currentPage,
  set: (value) => commentStore.setPagination(value, commentStore.pageSize)
})
const pageSize = computed({
  get: () => commentStore.pageSize,
  set: (value) => commentStore.setPagination(commentStore.currentPage, value)
})

// 方法
const handleSearch = () => {
  commentStore.setPagination(1, pageSize.value)
  loadCommentList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    rating: null,
    status: null,
    hasReply: null
  })
  handleSearch()
}

const handleRefresh = () => {
  loadCommentList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  loadCommentList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadCommentList()
}

const handleSelectionChange = (selection) => {
  selectedComments.value = selection
}

const handleBatchShow = async () => {
  try {
    const ids = selectedComments.value.map(comment => comment.id)
    await commentStore.batchUpdateCommentStatus(ids, 1)
    ElMessage.success('批量显示成功')
    selectedComments.value = []
  } catch (error) {
    console.error('批量显示失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

const handleBatchHide = async () => {
  try {
    const ids = selectedComments.value.map(comment => comment.id)
    await commentStore.batchUpdateCommentStatus(ids, 0)
    ElMessage.success('批量隐藏成功')
    selectedComments.value = []
  } catch (error) {
    console.error('批量隐藏失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}


const handleReply = (comment) => {
  selectedComment.value = comment
  replyDialogVisible.value = true
}

const handleUpdateStatus = async (comment, status) => {
  try {
    const action = status === 1 ? '显示' : '隐藏'
    await ElMessageBox.confirm(
        `确定要${action}这条评论吗？`,
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await commentStore.updateCommentStatus(comment.id, status)
    ElMessage.success(`${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新评论状态失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

const handleDelete = async (comment) => {
  try {
    await ElMessageBox.confirm(
        '确定要删除这条评论吗？此操作不可恢复！',
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }
    )

    await commentStore.deleteComment(comment.id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

const handleReplySuccess = () => {
  replyDialogVisible.value = false
  loadCommentList()
}

const previewImage = (imageUrl) => {
  previewImageUrl.value = imageUrl
  imagePreviewVisible.value = true
}

const formatCommentContent = (content) => {
  return commentStore.formatCommentContent(content, 100)
}

const loadCommentList = async () => {
  try {
    await commentStore.getCommentList(searchForm)
  } catch (error) {
    console.error('加载评论列表失败:', error)
    ElMessage.error('加载失败，请重试')
  }
}

// 生命周期
onMounted(() => {
  loadCommentList()
})
</script>

<style scoped>
.comment-content p {
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.comment-images {
  display: flex;
  gap: 4px;
  align-items: center;
}

.comment-image {
  width: 30px;
  height: 30px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #ddd;
}

.comment-image:hover {
  border-color: #409eff;
}

.more-images {
  font-size: 12px;
  color: #909399;
}

.merchant-reply p {
  margin: 0 0 4px 0;
  color: #606266;
  font-size: 14px;
}

.merchant-reply small {
  color: #909399;
  font-size: 12px;
}

.no-reply {
  color: #909399;
  font-style: italic;
}

.page-container {
  padding: var(--admin-space-lg);
  background: var(--admin-bg-layout);
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: var(--admin-space-lg);
  padding: var(--admin-space-lg);
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
  border: 1px solid var(--admin-border-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  color: var(--admin-text-primary);
  font-size: var(--admin-font-xl);
  font-weight: var(--admin-font-semibold);
  line-height: var(--admin-line-height-sm);
}

.table-container {
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
  border: 1px solid var(--admin-border-light);
  overflow: hidden;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
  padding: var(--admin-space-lg);
  background: var(--admin-bg-secondary);
  border-bottom: 1px solid var(--admin-border-light);
}

.table-toolbar-left {
  display: flex;
  gap: var(--admin-space-sm);
  align-items: center;
  flex-wrap: wrap;
}

.table-toolbar-right {
  display: flex;
  gap: var(--admin-space-sm);
  align-items: center;
  flex-wrap: wrap;
}

.pagination-container {
  padding: var(--admin-space-lg);
  text-align: center;
  background: var(--admin-bg-secondary);
  border-top: 1px solid var(--admin-border-light);
}

.image-preview-container {
  text-align: center;
}

/* 评分星级样式 */
.rating-container {
  display: flex;
  align-items: center;
  gap: var(--admin-space-sm);
  min-width: 120px;
}

.rating-container :deep(.el-rate) {
  display: flex;
  align-items: center;
}

.rating-container :deep(.el-rate__item) {
  margin-right: 2px;
}

.rating-container :deep(.el-rate__icon) {
  font-size: 14px;
}

.rating-text {
  font-size: var(--admin-font-xs);
  color: var(--admin-text-secondary);
  font-weight: var(--admin-font-medium);
  white-space: nowrap;
}

/* 评论图片样式 */
.comment-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: var(--admin-radius-sm);
  cursor: pointer;
  border: 1px solid var(--admin-border-light);
  transition: all 0.3s ease;
}

.comment-image:hover {
  border-color: var(--admin-primary);
  box-shadow: var(--admin-shadow-sm);
}

/* 商家回复样式 */
.merchant-reply {
  background: var(--admin-bg-secondary);
  padding: var(--admin-space-sm);
  border-radius: var(--admin-radius-sm);
  border-left: 3px solid var(--admin-primary);
  margin-top: var(--admin-space-xs);
}

.merchant-reply p {
  margin: 0 0 var(--admin-space-xs) 0;
  color: var(--admin-text-secondary);
  font-size: var(--admin-font-sm);
}

.merchant-reply small {
  color: var(--admin-text-tertiary);
  font-size: var(--admin-font-xs);
}

.no-reply {
  color: var(--admin-text-tertiary);
  font-style: italic;
  font-size: var(--admin-font-sm);
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: var(--admin-space-xs);
  align-items: center;
}

.action-buttons .el-button {
  padding: var(--admin-space-xs) var(--admin-space-sm);
  font-size: var(--admin-font-xs);
  height: var(--admin-height-sm);
  border-radius: var(--admin-radius-sm);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: var(--admin-space-md);
    align-items: flex-start;
  }

  .table-toolbar {
    flex-direction: column;
    gap: var(--admin-space-sm);
    align-items: stretch;
  }

  .table-toolbar-left,
  .table-toolbar-right {
    justify-content: center;
  }

  .action-buttons {
    flex-direction: column;
    width: 100%;
  }

  .action-buttons .el-button {
    width: 100%;
    justify-content: center;
  }
}
</style>
